package com.yang.springcloudalibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.yang.springcloud.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class StudentConsumerConterller {

    @Autowired
    private RestTemplate rte;

    private static final String REST_URL_PREFIX = "http://nacos-provider-student";

    @PostMapping("/consumer/student/insert")
    public Map<String, Object> addStudent(Student s){
        System.out.println(s.getId()+ " " + s.getName() + " " + s.getBirth() + " " + s.getSex());
        return rte.postForObject(REST_URL_PREFIX+"/insert", s, Map.class);
    }

    @PostMapping("/consumer/student/delete")
    public Map<String, Object> deleteStudent(String name){
        System.out.println(name);
        return rte.postForObject(REST_URL_PREFIX+"/delete", name, Map.class);

    }

    @PostMapping("/consumer/student/update")
    public Map<String, Object> updateStudent(Student s){
        return rte.postForObject(REST_URL_PREFIX+"/update", s, Map.class);

    }

    @GetMapping("/consumer/student/query")
    @SentinelResource(value = "queryStudent", fallback = "fallback", blockHandler = "handler") //fallback负责业务异常，blockHandler只负责sentinel控制台违规
    public List<Student> queryStudent(){
        //throw new RuntimeException("参数不能为空");
        return rte.getForObject(REST_URL_PREFIX+"/query",List.class);
    }

    public List<Student> fallback(){
        Student s = new Student("40", "fallback", "1", "女");
        List<Student> fList = new ArrayList<>();
        fList.add(s);
        return fList;
    }

    public List<Student> handler(){
        Student s = new Student("41", "handler", "2", "男");
        List<Student> hList = new ArrayList<>();
        hList.add(s);
        return hList;
    }
}
